package com.dyw.ycgovfinance.mvp.open;

import android.support.annotation.NonNull;

import com.dyw.ycgovfinance.bean.NewsKindBean;
import com.dyw.ycgovfinance.bean.NewsListBean;
import com.dyw.ycgovfinance.commom.Config;
import com.dyw.ycgovfinance.commom.TipStr;
import com.dyw.ycgovfinance.http.HttpService;
import com.dyw.ycgovfinance.http.HttpServiceUtil;
import com.dyw.ycgovfinance.mvp.news.newshome.NewsHomeContract;
import com.dyw.ycgovfinance.util.CalendarUtil;
import com.dyw.ycgovfinance.util.CommonUtil;
import com.dyw.ycgovfinance.util.LogUtil;
import com.dyw.ycgovfinance.util.schedulers.BaseSchedulerProvider;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.functions.FuncN;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by clboys on 2017/6/28.
 */


public class OpenMainPresenter implements OpenMainContract.Presenter {


    @NonNull
    OpenMainContract.View mView;

    @NonNull
    private final BaseSchedulerProvider mSchedulerProvider;

    @NonNull
    private final HttpService mHttpService;

    @NonNull
    private CompositeSubscription mSubscriptions;


    public OpenMainPresenter(@NonNull OpenMainContract.View view, @NonNull BaseSchedulerProvider mSchedulerProvider
            , @NonNull HttpService mHttpService) {
        this.mView = view;
        this.mSchedulerProvider = mSchedulerProvider;
        this.mHttpService = mHttpService;
        this.mSubscriptions = new CompositeSubscription();

        this.mView.setPresenter(this);
    }


    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mSubscriptions.unsubscribe();
        mSubscriptions = null;
    }


//    @Override
//    public void getNewsKind() {
//
//        mView.showLoading();
//
//        Subscription subscription = mHttpService.getNewsKind(HttpServiceUtil.makeRequestBody(makeParams()))
//                .subscribeOn(mSchedulerProvider.computation())
//                .observeOn(AndroidSchedulers.mainThread())
//                .filter(new Func1<JsonObject, Boolean>() {
//                    @Override
//                    public Boolean call(JsonObject jsonObject) {
//                        LogUtil.e("newsKind:" + jsonObject.toString());
//                        if (!jsonObject.get(HttpServiceUtil.RESOIBSE_KEY_CODE).getAsString().equals(HttpServiceUtil.RESOIBSE_STATE_SUCCESS)) {
//                            mView.dismissLoading();
//                            mView.onGetNewsKindError(jsonObject.get(HttpServiceUtil.RESOIBSE_KEY_MESSAGE).getAsString());
//
//                        }
//                        return jsonObject.get(HttpServiceUtil.RESOIBSE_KEY_CODE).getAsString().equals(HttpServiceUtil.RESOIBSE_STATE_SUCCESS);
//                    }
//                })
//                .subscribe(new Subscriber<JsonObject>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        e.printStackTrace();
//                        mView.dismissLoading();
//                        mView.onGetNewsKindError(TipStr.TIP_SERVER_GET_DATA_WRONG);
//                    }
//
//                    //onNext是当执行结果正确的时候执行的地方
//                    @Override
//                    public void onNext(JsonObject jsonObject) {
//
//                        List<NewsKindBean> newsKindBeanList = CommonUtil.formatJsonToObject(jsonObject,"lmcodeList",new TypeToken<List<NewsKindBean>>(){});
//
//                        mView.dismissLoading();
//                        mView.onGetNewsKindSuccess(newsKindBeanList);
//                    }
//                });
//    }


    public Map<String, String> makeGetOpenNewsKindParams() {
        String nowTime = CalendarUtil.calendar2String3(Calendar.getInstance());

        List<String> signParamsList = new ArrayList<>();
        signParamsList.add("deviceType");
        signParamsList.add("time");


        List<String> signValuesList = new ArrayList<>();
        signValuesList.add(Config.DEVICE_TYPE);
        signValuesList.add(nowTime);

        LogUtil.e("deviceType:" + Config.DEVICE_TYPE);
        LogUtil.e("time:" + nowTime);

        String signStr = HttpServiceUtil.getSignValue(signParamsList, signValuesList);

        Map<String, String> requestParams = new HashMap<>();
        requestParams.put("sign", signStr);
        requestParams.put("deviceType", Config.DEVICE_TYPE);
        requestParams.put("time", nowTime);

        return (HashMap<String, String>) requestParams;
    }

    @Override
    public void getOpenNewsKind() {
        mView.showLoading();

        Subscription subscription = mHttpService.getOpenNewsKind(HttpServiceUtil.makeRequestBody(makeGetOpenNewsKindParams()))
                .subscribeOn(mSchedulerProvider.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Func1<JsonObject, Boolean>() {
                    @Override
                    public Boolean call(JsonObject jsonObject) {
                        LogUtil.e("opennewsKind:" + jsonObject.toString());
                        if (!jsonObject.get(HttpServiceUtil.RESOIBSE_KEY_CODE).getAsString().equals(HttpServiceUtil.RESOIBSE_STATE_SUCCESS)) {
                            mView.dismissLoading();
                            mView.onGetOpenNewsKindError(jsonObject.get(HttpServiceUtil.RESOIBSE_KEY_MESSAGE).getAsString());

                        }
                        return jsonObject.get(HttpServiceUtil.RESOIBSE_KEY_CODE).getAsString().equals(HttpServiceUtil.RESOIBSE_STATE_SUCCESS);
                    }
                })
                .subscribe(new Subscriber<JsonObject>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        mView.dismissLoading();
                        mView.onGetOpenNewsKindError(TipStr.TIP_SERVER_GET_DATA_WRONG);
                    }

                    //onNext是当执行结果正确的时候执行的地方
                    @Override
                    public void onNext(JsonObject jsonObject) {

                        List<NewsKindBean> commonNewsKinds = CommonUtil.formatJsonToObject(jsonObject, "lmcodeList", new TypeToken<List<NewsKindBean>>() {
                        });

                        NewsKindBean govJsNewsKind = (NewsKindBean) CommonUtil.formatJsonToObject2(jsonObject, "zfjs", new TypeToken<NewsKindBean>() {
                        });
                        NewsKindBean govYsNewsKind = (NewsKindBean) CommonUtil.formatJsonToObject2(jsonObject, "zfys", new TypeToken<NewsKindBean>() {
                        });

                        NewsKindBean depaetJsNewsKind = (NewsKindBean) CommonUtil.formatJsonToObject2(jsonObject, "bmjs", new TypeToken<NewsKindBean>() {
                        });
                        NewsKindBean depaetYsNewsKind = (NewsKindBean) CommonUtil.formatJsonToObject2(jsonObject, "bmys", new TypeToken<NewsKindBean>() {
                        });


                        mView.dismissLoading();
                        mView.onGetOpenNewsKindSuccess(commonNewsKinds, govYsNewsKind, govJsNewsKind, depaetYsNewsKind, depaetJsNewsKind);
                    }
                });
    }

    @Override
    public void getAllNewsList(String defaultPageIndex, String defaultPageSize, final List<NewsKindBean> newsKindList) {

        List<Observable<JsonObject>> getAllNewsObserverList = new ArrayList<>();

        for (int i = 0; i < newsKindList.size(); i++) {
            NewsKindBean curNewsKind = newsKindList.get(i);
            getAllNewsObserverList.add(
                    mHttpService.getNewsList(HttpServiceUtil.makeRequestBody(makeGetNewsListParams(defaultPageIndex, defaultPageSize, curNewsKind.getTtype(), curNewsKind.getTclass()))));
        }


        Observable.zip(getAllNewsObserverList, new FuncN<List<JsonObject>>() {
            @Override
            public List<JsonObject> call(Object... args) {

               /* Map<String,JsonObject> resultMap = new HashMap<String, JsonObject>();

                for (int i = 0;i<args.length;i++)
                {
                    resultMap.put(newsKindList.get(0).getName(),(JsonObject) args[i]);
                }*/

               List<JsonObject> resultJsonObjectList = new ArrayList<JsonObject>();
                for (int i = 0;i<args.length;i++)
                {
                    resultJsonObjectList.add((JsonObject) args[i]);
                    //resultMap.put(newsKindList.get(0).getName(),(JsonObject) args[i]);
                }


                return resultJsonObjectList;
            }
        }).subscribeOn(mSchedulerProvider.computation())//在新线程中实现该方法
                .observeOn(AndroidSchedulers.mainThread())//在Android主线程中展示
                .doOnNext(new Action1<List<JsonObject>>() {
                    @Override
                    public void call(List<JsonObject> resultJsonObjList) {

                        for (JsonObject jsonObject:
                                resultJsonObjList) {
                            if (!jsonObject.get(HttpServiceUtil.RESOIBSE_KEY_CODE).getAsString().equals(HttpServiceUtil.RESOIBSE_STATE_SUCCESS)) {
                                mView.dismissLoading();
                                mView.onGetAllNewsListError(jsonObject.get(HttpServiceUtil.RESOIBSE_KEY_MESSAGE).getAsString());
                                break;
                            }
                        }
                    }
                })
                .subscribe(new Subscriber<List<JsonObject>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        mView.dismissLoading();
                        mView.onGetAllNewsListError(TipStr.TIP_SERVER_GET_DATA_WRONG);


                    }

                    @Override
                    public void onNext(List<JsonObject> resultJsonList) {

                        Map<String,List<NewsListBean>> newsListHashMap = new HashMap<String, List<NewsListBean>>();
                        for (int i = 0;i<resultJsonList.size(); i++) {
                            List<NewsListBean> newsList = CommonUtil.formatJsonToObject(resultJsonList.get(i),"jhInfoList",new TypeToken<List<NewsListBean>>(){});
                            newsListHashMap.put(newsKindList.get(i).getName(),newsList);
                        }

                        mView.onGetAllNewsListSuccess((HashMap<String, List<NewsListBean>>) newsListHashMap);
                    }
                });


    }

    /*@Override
    public void getOpenNewsList(String pageIndex,String pageSize,String newsKindName,String newsKindParentTag,String newsKindSonTag) {

    }*/

    public Map<String, String> makeGetNewsListParams(String pageIndex, String pageSize, String newsKindParentTag, String newsKindSonTag) {
        String nowTime = CalendarUtil.calendar2String3(Calendar.getInstance());

        List<String> signParamsList = new ArrayList<>();
        signParamsList.add("deviceType");
        signParamsList.add("time");
        signParamsList.add("currentPage");
        signParamsList.add("numPerPage");
        signParamsList.add("ttype");
        signParamsList.add("tclass");

        List<String> signValuesList = new ArrayList<>();
        signValuesList.add(Config.DEVICE_TYPE);
        signValuesList.add(nowTime);
        signValuesList.add(pageIndex);
        signValuesList.add(pageSize);
        signValuesList.add(newsKindParentTag);
        signValuesList.add(newsKindSonTag);


        String signStr = HttpServiceUtil.getSignValue(signParamsList, signValuesList);

        Map<String, String> requestParams = new HashMap<>();
        requestParams.put("sign", signStr);
        requestParams.put("deviceType", Config.DEVICE_TYPE);
        requestParams.put("time", nowTime);
        requestParams.put("currentPage", pageIndex);
        requestParams.put("numPerPage", pageSize);
        requestParams.put("ttype", newsKindParentTag);
        requestParams.put("tclass", newsKindSonTag);

        return (HashMap<String, String>) requestParams;
    }
}

